class GroupsController < ApplicationController

  before_filter :must_be_admin, :except => [:index]

  def index
    @groups = Group.all
  end

  def new
    @group = Group.new
  end

  def create
    @group = Group.new(params[:group])
    if @group.save
      flash[:success] = "• 『#{@group.name}』组的基本资料保存成功!"
      redirect_to :action => :index
    else
      render :new 
    end
  end

  def edit
    @group = Group.find(params[:id])
  end

  def update
    @group = Group.find(params[:id])
    if @group.update_attributes(params[:group])
      flash[:success] = "• 『#{@group.name}』组的基本资料更新成功!"
      redirect_to :action => :index
    else
      render :new 
    end
  end

  def destroy
    @group = Group.find(params[:id])
    @group.destroy
    flash[:success] = "• 『#{@group.name}』组删除成功!"
    redirect_to :action => :index
  end

  def sort
    params[:group].each_with_object([]) do |group_id,groups|
      groups << Group.find(group_id)
    end.each_with_index do |group,index|
      group.position!( index + 1)
    end
    render :text => 'success'
  end
end
